package com.dean.service.impl;

import com.dean.exception.DeanRuntimeException;
import com.dean.service.DeanExcelExportService;
import com.dean.utils.DeanExcelParseUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

public class DeanXlsExportServiceImpl implements DeanExcelExportService {
    private static final Logger logger = LoggerFactory.getLogger(DeanXlsExportServiceImpl.class);
    @Override
    public void exportExcel(String tempName, OutputStream outputStream, Map<String, Object> context) {
    // step1: 读取excel 模板
        try(Workbook workbook = WorkbookFactory.create(new FileInputStream(tempName))){
            // 获取有多少个sheet
            int sheetNums = workbook.getNumberOfSheets();
            // 读取所有sheet页
            for (int i = 0; i < sheetNums; i++) {
                // 获取 sheet
                Sheet sheet = workbook.getSheetAt(i);
                // 获取有多少行记录
                int lastRownum = sheet.getLastRowNum()+1;
                for (int j = 0; j < lastRownum; j++) {
                    // 读取行数据
                    Row row = sheet.getRow(j);
                    // 获取改行有多少列
                    short lastCellNum = row.getLastCellNum();
                    for (int k = 0; k < lastCellNum; k++) {
                        // 获取单元格
                        Cell cell = row.getCell(k);
                        // 单元格为空的直接跳过
                        if(cell == null){
                            continue;
                        }
                        // 单元格不是String类型的都不要 应为设置参数都会被认为字符串
                        if(cell.getCellType()!=CellType.STRING){
                            continue;
                        }
                        String value = cell.getStringCellValue();

                        // 看看是不是需要解析的模板参数
                        if(value.startsWith("${") && value.endsWith("}")){
                            // 去掉模板包含的字符
                            String param = value.substring(2,value.length()-1);
                            // 解析参数
                            Object val = DeanExcelParseUtils.deanParse(param,context);
                            // 优先将参数转换成字符串
                            String newVal = val == null ? "" : val.toString();
                            // 判断是否数字 赋值
                            if(NumberUtils.isParsable(newVal)){
                                cell.setCellValue(new Double(newVal));
                            }else{
                                cell.setCellValue(newVal);
                            }
                        }else{
                            continue;
                        }
                    }
                }
            }
            // 按照表格公式重新计算
            workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
            // 将文件写入到输出流
            // OutputStream outputStream = new FileOutputStream(result);
            workbook.write(outputStream);

        } catch (FileNotFoundException e) {
            DeanRuntimeException.throwException(996,"没有找到模板文件");
            logger.error(e.getMessage(),e);
        } catch (IOException e) {
            DeanRuntimeException.throwException(996,"读取模板发生异常");
            logger.error(e.getMessage(),e);
        }
    }
}
